package com.chatplus.application.aiprocessor.platform.chat.aliyun;

import cn.bugstack.openai.executor.model.aliyun.config.AliModelConfig;
import cn.bugstack.openai.executor.parameter.CompletionRequest;
import cn.bugstack.openai.session.Configuration;
import cn.bugstack.openai.session.OpenAiSession;
import cn.bugstack.openai.session.OpenAiSessionFactory;
import cn.bugstack.openai.session.defaults.DefaultOpenAiSessionFactory;
import com.chatplus.application.aiprocessor.listener.CommonEventSourceListener;
import com.chatplus.application.aiprocessor.platform.chat.ChatProcessorService;
import com.chatplus.application.aiprocessor.provider.ChatAiProcessorServiceProvider;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.ws.ChatRecordMessage;
import com.chatplus.application.enumeration.AiPlatformEnum;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 阿里云 通义千问 机器人处理器
 * <p>
 * @Author Angus
 */
@Service(value = ChatAiProcessorServiceProvider.SERVICE_NAME_PRE + "QWen")
public class AliYunQWenProcessor extends ChatProcessorService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(AliYunQWenProcessor.class);
    @Override
    public void processStream() throws Exception {
        CompletionRequest request = getCompletionRequest();
        OpenAiSession openAiSession = getSessionFactory();
        if (openAiSession != null) {
            openAiSession.completions(request, new CommonEventSourceListener(chatRequest));
        }
    }
    @Override
    public String processSync() {
        return null;
    }

    @Override
    public AiPlatformEnum getChannel() {
        return AiPlatformEnum.ALI_YUN_Q_WEN;
    }

    @Override
    public void initSessionFactory() {
        instance();
        OPEN_API_KEY_CACHE.forEach(item -> {

            String apiKey = item.getApiKey();
            AliModelConfig aliModelConfig = new AliModelConfig();
            aliModelConfig.setApiHost(item.getUrl());
            aliModelConfig.setApiKey(apiKey);
            // 2. 配置文件
            Configuration configuration = new Configuration();
            configuration.setLevel(HttpLoggingInterceptor.Level.HEADERS);
            configuration.setAliModelConfig(aliModelConfig);
            configuration.setProxyUrl(item.getProxyUrl());
            // 3. 会话工厂
            OpenAiSessionFactory factory = new DefaultOpenAiSessionFactory(configuration);
            OPEN_AI_SESSION_CACHE.put(getChannel(), factory.openSession());
        });
    }
}
